package ru.nosport.matrixaria;

import ru.nosport.matrixaria.core.Init;
import ru.nosport.matrixaria.core.InitException;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * User: vfabr
 * Date: 18.10.2006
 * Time: 13:51:11
 */
public class MatrixariaMain implements Runnable {
	private String confPath;
	private Init init;
	private volatile boolean isStarted;
	private static MatrixariaMain ourInstance;
	private ExecutorService exec;

	/**
	 *
	 * @param _path -
	 */
	public static void initialize(String _path) {
		if (ourInstance == null) {
			ourInstance = new MatrixariaMain(_path);
		}
	}

	/**
	 *
	 * @return -
	 */
	public static MatrixariaMain getInstance() {
		if (ourInstance != null) {
			return ourInstance;
		}
		return null;
	}

	/**
	 *
	 * @param _path -
	 */
	private MatrixariaMain(String _path) {
		this.confPath = _path;
		this.isStarted = false;
		this.exec = Executors.newSingleThreadExecutor();
	}

	/**
	 *
	 */
	public void startServer() {
		if (!this.isStarted) {
			try {
				this.init = new Init(this.confPath);
				this.isStarted = true;
				this.exec.execute(this);
			} catch (InitException _ex) {
				System.out.println("------------------");
				System.out.println("Start server error: ");
				_ex.printStackTrace();
				System.out.println("------------------");
				this.isStarted = false;
			}
		}
	}

	/**
	 *
	 * @return -
	 */
	public boolean stopServer() {
		boolean ret = false;
		if (this.isStarted) {
			this.isStarted = false;
			try {
				this.init.unInit();
				ret = true;
			} catch (InitException _ex) {
				System.out.println("------------------");
				System.out.println("Stor server error: ");
				_ex.printStackTrace();
				System.out.println("------------------");
				ret = false;
			}
		}
		return ret;
	}

	/**
	 *
	 */
	public void shutdownServer() {
		this.stopServer();
		this.isStarted = false;
	}

	/**
	 * 
	 */
	public void run() {
		while(this.isStarted) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException _ex) {
				System.out.println("Main thread terminated!");
				ourInstance = null;
			}
		}
	}
}
